package net.chasing.androidbaseconfig.util.html;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import net.chasing.androidbaseconfig.R;

public class HtmlLoadUtils {
    public static String convertHtml(String htmlText) {
        if (TextUtils.isEmpty(htmlText)) {
            return htmlText;
        }
        return HtmlParser.buildSpannedText(htmlText, new CustomerTagHandler()).toString();
    }

    public static void loadHtmlText(Context context, TextView tv, String htmlText) {
        if (TextUtils.isEmpty(htmlText)) {
            tv.setText("");
            return;
        }
        tv.setText(HtmlParser.buildSpannedText(htmlText, new MyImageGetter(context, tv), new CustomerTagHandler()).toString());
        textHtmlClick(context, tv);
    }

    public static void loadHtmlTextWithoutImage(TextView tv, String htmlText) {
        if (TextUtils.isEmpty(htmlText)) {
            tv.setText("");
            return;
        }
        tv.setText(HtmlParser.buildSpannedText(htmlText, new CustomerTagHandler()).toString());
    }

    /**
     * 处理html文本超链接点击事件
     */
    private static void textHtmlClick(Context context, TextView tv) {
        tv.setMovementMethod(LinkMovementMethod.getInstance()); // 设置可滚动/拦截点击等
        CharSequence text = tv.getText();
        if (text instanceof Spannable) {
            int end = text.length();
            Spannable sp = (Spannable) text;
            URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.clearSpans();// should clear old spans
            for (URLSpan url : urls) {
                MyURLSpan myURLSpan = new MyURLSpan(url.getURL(), context);
                style.setSpan(myURLSpan, sp.getSpanStart(url),
                        sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            }
            tv.setText(style);
        }
    }

    public static class MyURLSpan extends ClickableSpan {
        private final String mUrl;
        private final Context mContext;

        MyURLSpan(String url, Context context) {
            mContext = context;
            mUrl = url;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ContextCompat.getColor(mContext, R.color.emotion_selected_bg));
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(@NonNull View widget) {
//            WebViewActivity.start(mContext, mUrl);
        }
    }
}
